package com.auth.manage.base.util;

import cn.hutool.core.exceptions.ValidateException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import org.hibernate.validator.HibernateValidator;

import java.util.Set;
import java.util.function.Consumer;

// SpringMVC的DispatchServlet的ArgumentResolver组件可以识别Validation的注解，从而调用Validator进行校验,Service层要实现类似效果就需要手动定义该校验类校验，并在类上加上@Validated，在需要校验的方法参数上加上@Valid
public class BeanValidator {
    // failFast(true)：默认情况会检查所有字段，设置为true后只要找到第一个错误就立刻停止校验并返回，因此Set<ConstraintViolation<Object>>只有一条数据
    private static Validator validator = Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();

    // 参数1:要被校验的对象 参数2：本次校验想启动的分组 返回值：Set<ConstraintViolation<Object>>：所有校验不通过的明细列表
    public static void validateObject(Object object, Class<?> ...groups){
        Set<ConstraintViolation<Object>> validate = validator.validate(object, groups);
        validate.stream().findFirst().ifPresent(new Consumer<ConstraintViolation<Object>>() {
            @Override
            public void accept(ConstraintViolation<Object> objectConstraintViolation) {
                throw new ValidateException(objectConstraintViolation.getMessage());
            }
        });

    }
}
